//
//  WechatLogin.m
//  OpenSDK
//
//  Created by 涂俊 on 2020/2/11.
//  Copyright © 2020 WYHT. All rights reserved.
//

#import "WechatLogin.h"

//#import "WXApi.h"
#import "WCMApi.h"
#import "OpenSDK_EventManager.h"
#import "OpenSDK_EventKeys.h"
#import "OpenSDK_DataKeys.h"
#import "OpenSDK_Toast.h"
#import "OpenSDK_UIUtil.h"
#import "OpenSDK_HttpUtil.h"



//@interface WechatLogin() <WXApiDelegate>
@interface WechatLogin() <WCMApiDelegate>
@property(nonatomic, assign)BOOL isLogin;
@property(nonatomic, strong)NSString *respCode;
@end

@implementation WechatLogin

static NSString *APP_CONFIG=@"WcAppId";

- (NSString *)getServerName {
    return @"WeChatLogin";
}

- (void)initInfo {
    [OpenSDK_EventManager addObsver:self selector:@selector(initSDK:) name:OPENSDK_EVENT_INIT object:nil className:@"WechatLogin"];
    [OpenSDK_EventManager addObsver:self selector:@selector(application_handleOpenURL:) name:OPENSDK_EVENT_APPLICATION_HANDLEOPENURL object:nil className:@"WechatLogin"];
    [OpenSDK_EventManager addObsver:self selector:@selector(application_openURL_options:) name:OPENSDK_EVENT_APPLICATION_OPENURL_OPTIONS object:nil className:@"WechatLogin"];
    [OpenSDK_EventManager addObsver:self selector:@selector(application_openURL_sourceApplication_annotation:) name:OPENSDK_EVENT_APPLICATION_OPENURL_SOURCEAPPLICATION_ANNOTATION object:nil className:@"WechatLogin"];
    [OpenSDK_EventManager addObsver:self selector:@selector(application_continue_userActivity:) name:OPENSDK_EVENT_APPLICATION_CONTINUEUSERACTIVITY object:nil className:@"WechatLogin"];
}

- (NSString *)getBackgroundImage {
    return @"op_login_type_wx_bg";
}

- (NSString *)getDisplayIcon {
    return @"op_login_type_wx";
}

- (NSString *)getDisplayName {
    return @"微信";
}

-(NSString *) getDisplaySdkName {
    return @"微信";
}

- (NSString *)getPlatform {
    return @"WeChatLogin";
}

- (NSString *)getPlatformVersion {
    return @"1.0";
}


#pragma mark - 接口实现，调起登录
- (void)startLogin {
    _isLogin = YES;
    [self openWX];
}

- (void)startAuth {
    _isLogin = NO;
    [self openWX];
}


- (void)openWX {
    // 调起登录
    dispatch_async(dispatch_get_main_queue(), ^{
        //判断微信是否安装
//        if ([WXApi isWXAppInstalled]) {
//            SendAuthReq *req = [[SendAuthReq alloc] init];
//            req.scope = @"snsapi_userinfo";
//            req.state = @"OpenSDK";
//            [WXApi sendAuthReq:req viewController:[OpenSDK_UIUtil getCurrentVC] delegate:self completion:^(BOOL success) {
//                //
//            }];
//        }
        if ([WCMApi isWXAppInstalled]) {
            SendAuthReq *req = [[SendAuthReq alloc] init];
            req.scope = @"snsapi_userinfo";
            req.state = @"OpenSDK";
            [WCMApi sendAuthReq:req viewController:[OpenSDK_UIUtil getCurrentVC] delegate:self completion:^(BOOL success) {
                //
            }];
        }
        else {
            if (self.loginDelegate) {
                OpenSDK_BaseResData *resData = [[OpenSDK_BaseResData alloc] init];
                [resData fail];
                [resData setErrorMsg:@"抱歉，未安装微信，无法进行微信登录"];
                [resData setErrorNo:OpenSDK_SDK_LOGIN_FAILED];
                self.loginDelegate(resData);
            }
        }
    });
}

#pragma mark - OpenSDK初始化时，初始化微信
-(void) initSDK:(NSNotification*) notification {
    // 微信appId
    NSString *appId = [[[[NSBundle mainBundle] infoDictionary] objectForKey:OpenSDK_CONFIG] objectForKey:APP_CONFIG];
    NSString *universalLinks = [[[[NSBundle mainBundle] infoDictionary] objectForKey:OpenSDK_CONFIG] objectForKey:OpenSDK_UNIVERSAL_LINKS];
    [WCMApi registerApp:appId universalLink:universalLinks];
//    [WXApi registerApp:appId universalLink:universalLinks];
}

#pragma mark - 微信回调需要添加的代码，在系统生命周期回调函数
-(void) application_handleOpenURL:(NSNotification*) notification {
    NSLog(@"WechatLogin:application_handleOpenURL");
    NSURL *url = [[notification object] objectForKey:OpenSDK_E_OPENURL];
    [WCMApi handleOpenURL:url delegate:self];
//    [WXApi handleOpenURL:url delegate:self];
}

#pragma mark - 微信回调需要添加的代码，在系统生命周期回调函数
-(void) application_openURL_sourceApplication_annotation:(NSNotification*) notification {
    NSLog(@"WechatLogin:application_openURL_sourceApplication_annotation");
    NSURL *url = [[notification object] objectForKey:OpenSDK_E_OPENURL];
    [WCMApi handleOpenURL:url delegate:self];
//    [WXApi handleOpenURL:url delegate:self];
}

#pragma mark - universal links 回调
-(void) application_continue_userActivity:(NSNotification*) notification {
    NSLog(@"WechatLogin:application_continue_userActivity");
    NSUserActivity *userActivity = [[notification object] objectForKey:OpenSDK_E_USERACTIVITY];
    [WCMApi handleOpenUniversalLink:userActivity delegate:self];
//    [WXApi handleOpenUniversalLink:userActivity delegate:self];
}

#pragma mark - 微信回调需要添加的代码，在系统生命周期回调函数
// NOTE: 9.0以后使用新API接口
-(void) application_openURL_options:(NSNotification*) notification {
    NSLog(@"WechatLogin:application_openURL_options");
    NSURL *url = [[notification object] objectForKey:OpenSDK_E_OPENURL];
    [WCMApi handleOpenURL:url delegate:self];
//    [WXApi handleOpenURL:url delegate:self];
}

#pragma mark - WXApiDelegate
- (void)onResp:(BaseResp *)resp{
    if ([resp isKindOfClass:[SendAuthResp class]]) {
        SendAuthResp *resp2 = (SendAuthResp *)resp;
        NSString *code = resp2.code;
        if (code == nil) { return; }
        if ([code isEqual:_respCode]) { return; }
        _respCode = code;
        if (_isLogin) {
            [OpenSDK_HttpUtil loginWithOtherSDK:@{@"code":code}
                                       platform:[self getPlatform]
                                platformVersion:[self getPlatformVersion]
                                   httpDelegate:self.loginDelegate];
        } else {
            if (self.loginDelegate) {
                OpenSDK_BaseResData *data = [[OpenSDK_BaseResData alloc] init];
                data.status = @"ok";
                data.content = @{@"code": code,
                                 @"oauth_type": [self getPlatform],
                                 @"platform_version": [self getPlatformVersion]}.mutableCopy;
                self.loginDelegate(data);
            }
        }
        
    } else {
//        dispatch_async(dispatch_get_main_queue(), ^{
//            if (self.loginDelegate) {
//                OpenSDK_BaseResData *resData = [[OpenSDK_BaseResData alloc] init];
//                [resData fail];
//                [resData setErrorMsg:@"抱歉，微信登录授权登录失败"];
//                [resData setErrorNo:OpenSDK_SDK_LOGIN_FAILED];
//                self.loginDelegate(resData);
//            }
//        });
    }
}

@synthesize loginDelegate;

@end
